package com.danton.user.service.impl;

import java.util.List;

import com.danton.model.BsPermissionModel;
import com.danton.model.BsRoleModel;
import com.danton.model.BsRolePermissionModel;
import com.danton.user.service.PermissionService;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class PermissionServiceImpl implements PermissionService {

	@Override
	public Page<BsPermissionModel> list(int pageNumber, int pageSize) {
		return BsPermissionModel.dao.paginate(pageNumber, pageSize);
	}

	@Override
	public boolean add(BsPermissionModel permissionModel) {
		String description = String.valueOf(permissionModel.get("description"));
		String id=findId(description);
		if(id==null || ("".equals(id))){
			return permissionModel.save();
		}
		return false;
	}

	@Override
	public boolean edit(BsPermissionModel permissionModel) {
		String description = String.valueOf(permissionModel.get("description"));
		String permission_id = String.valueOf(permissionModel.get("permission_id"));
	    boolean flag = findByIDAndName(description,permission_id);
		if(flag){
			return permissionModel.update();
		}
		return false;
	}

	@Override
	public List<BsPermissionModel> findByRoleID(int role_id) {
		return BsPermissionModel.dao.findPermissionsByRoleID(role_id);
	}

	@Override
	public List<BsPermissionModel> findRoleID(int role_id) {
		return BsPermissionModel.dao.findPermissionByRoleID(role_id);
	}

	@Override
	public String findId(String name) {
		String sql="select id from bs_permission where description="+"'"+name+"'";
		 List<BsPermissionModel> perlist = BsPermissionModel.dao.find(sql);
		 String id = null;
		 for(BsPermissionModel per:perlist){
			 id=String.valueOf(per.get("id"));
		 }
		 return id;
	}

	@Override
	public boolean findByIDAndName(String description, String persission_id) {
		String sql = "select * from bs_permission where id=" + "'" + persission_id + "'"+" and description="+"'"+description+"'";
		List<BsPermissionModel> list = BsPermissionModel.dao.find(sql);
		if (list.size()== 0) {
			return	true;
		}
		return false;
	}

	@Override
	public List<Record> listAllModule() {
		return BsPermissionModel.dao.listAllModule();
	}

	@Override
	public List<BsPermissionModel> listAllPermissionByModule(String module) {
		return BsPermissionModel.dao.listAllPermissionByModule(module);
	}

	@Override
	public List<BsPermissionModel> listRolePermissionByModule(int role_id, String module) {
		return BsPermissionModel.dao.listRolePermissionByModule(role_id,module);
	}

	@Override
	public List<Record> listRoleModule(int role_id) {
		return BsPermissionModel.dao.listRoleModule(role_id);
	}
}
